package com.example.demo.grbkxt.dao;

import com.example.demo.grbkxt.model.Blog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class BlogDao {
    // 修改为项目根目录下的 data 目录
    private static final String DATA_DIR = System.getProperty("user.dir") + File.separator + "data";
    private static final String DATA_FILE = DATA_DIR + File.separator + "blogs.json";
    private static final Gson gson = new Gson();

    public BlogDao() {
        // 确保数据目录存在
        File dir = new File(DATA_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        System.out.println("数据文件路径: " + DATA_FILE); // 添加日志便于查看文件位置
    }

    public List<Blog> getAllBlogs() {
        try (Reader reader = new FileReader(DATA_FILE)) {
            Type type = new TypeToken<List<Blog>>() {
            }.getType();
            return gson.fromJson(reader, type);
        } catch (IOException e) {
            return new ArrayList<>();
        }
    }

    public void saveBlogs(List<Blog> blogs) {
        try (Writer writer = new FileWriter(DATA_FILE)) {
            gson.toJson(blogs, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Blog getBlogById(String id) {
        List<Blog> blogs = getAllBlogs();
        Blog foundBlog = blogs.stream()
                .filter(blog -> blog.getId().equals(id))
                .findFirst()
                .orElse(null);

        System.out.println("Found blog category: " + (foundBlog != null ? foundBlog.getCategory() : "null")); // 添加调试日志
        return foundBlog;
    }

    public void addBlog(Blog blog) {
        List<Blog> blogs = getAllBlogs();
        blogs.add(blog);
        saveBlogs(blogs);
    }

    public void updateBlog(Blog updatedBlog) {
        List<Blog> blogs = getAllBlogs();
        for (int i = 0; i < blogs.size(); i++) {
            if (blogs.get(i).getId().equals(updatedBlog.getId())) {
                // 确保保存分类信息
                if (updatedBlog.getCategory() == null) {
                    updatedBlog.setCategory(blogs.get(i).getCategory());
                }
                blogs.set(i, updatedBlog);
                break;
            }
        }
        saveBlogs(blogs);
    }

    public void deleteBlog(String id) {
        List<Blog> blogs = getAllBlogs();
        blogs.removeIf(blog -> blog.getId().equals(id));
        saveBlogs(blogs);
    }

    public List<Blog> getPublicBlogs() {
        List<Blog> allBlogs = getAllBlogs();
        return allBlogs.stream()
                .filter(blog -> !blog.isAdminOnly())
                .collect(Collectors.toList());
    }

    public List<Blog> searchBlogs(String keyword, String category) {
        List<Blog> allBlogs = getPublicBlogs();
        final String searchKeyword = (keyword == null) ? "" : keyword.toLowerCase();
        final String searchCategory = (category == null) ? "" : category;

        return allBlogs.stream()
                .filter(blog -> {
                    boolean matchesKeyword = searchKeyword.isEmpty() ||
                            blog.getTitle().toLowerCase().contains(searchKeyword) ||
                            blog.getContent().toLowerCase().contains(searchKeyword);
                    boolean matchesCategory = searchCategory.isEmpty() ||
                            searchCategory.equals(blog.getCategory());
                    return matchesKeyword && matchesCategory;
                })
                .collect(Collectors.toList());
    }
}
